//
//  MYAudioManager.m
//  JQLive
//
//  Created by Bruce on 2020/7/16.
//  Copyright © 2020 mlqk. All rights reserved.
//

#import "MYAudioManager.h"
#import "AFURLSessionManager.h"

#define MYMP3FileName  @"MP3File"
@interface MYAudioManager ()
{
    NSString *allFilePath;
}
@end
@implementation MYAudioManager
//设置单例
+ (MYAudioManager *)sharedManager
{
    static MYAudioManager *manager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MYAudioManager alloc] init];
        [manager creatFile];
    });
    return manager;
}

- (void)creatFile
{
    NSArray *firstPathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);//获取沙河路径

    NSString *firthPath = [firstPathArray firstObject];//获取缓存


    allFilePath = [firthPath stringByAppendingPathComponent:MYMP3FileName];//创建一个MP3File文件夹，

    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];

    BOOL isExisted = [fileManager fileExistsAtPath:allFilePath isDirectory:&isExisted];//坚持文件夹是否存在

    if (!(isDir == YES && isExisted == YES)) {//确保文件夹一定会被创建成果，以便于音频文件的存储

    [fileManager createDirectoryAtPath:allFilePath withIntermediateDirectories:YES attributes:nil error:nil];

    }

  
}

- (BOOL)checkIsDownloaded:(MYAudioModel *)model
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager createDirectoryAtPath:allFilePath withIntermediateDirectories:YES attributes:nil error:nil];;//拷贝创建的文件夹
    
    NSString *fileName = [model.url lastPathComponent];
    NSString *tempString = [[fileName componentsSeparatedByString:@"."]firstObject];

    NSString *secString =[[fileName componentsSeparatedByString:@"."]lastObject];

    NSString *destinationFile = [[JQLiveTools md5:tempString] stringByAppendingString:[NSString stringWithFormat:@".%@",secString]];
    
    NSString *lastPath = [allFilePath stringByAppendingPathComponent:destinationFile];

    BOOL isExistTheMp3File = [fileManager fileExistsAtPath:lastPath];//判断文件是否存在

    if (isExistTheMp3File) {
        model.localPath = lastPath;

    return YES;

    }
    model.localPath = @"";
    return NO;
   
}
- (void)downLoad:(MYAudioModel *)model  withIndex:(NSInteger)index
 successBlock:(void (^)(NSInteger index))block
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    AFURLSessionManager  *sessionManager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];

    NSURLRequest *requestSound = [NSURLRequest requestWithURL:[NSURL URLWithString:model.url]];//生成request文件

    NSURLSessionDownloadTask *downloadTask = [sessionManager downloadTaskWithRequest:requestSound progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {//此代码块中需要返回的是最终生成音频存储文件的二进制文件，所以和上边生成存储的是一样的文件，不同的是此代码块自动转二进制，不需要人为操纵。

    NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];

//    这里通过相应文件的.进行分割，旨在获取通过获取前半部分字符串来加密，从而确保文件夹中存放的音频文件和准备下载所生成的代码完全一致，从而更好的读取本地文件

    NSString *tempString = [[[response suggestedFilename]componentsSeparatedByString:@"."]firstObject];

    NSString *secString =[[[response suggestedFilename]componentsSeparatedByString:@"."]lastObject];

    NSString *lastName = [[JQLiveTools md5:tempString] stringByAppendingString:[NSString stringWithFormat:@".%@",secString]];
        
    return [downloadURL URLByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",MYMP3FileName,lastName]];

    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

    //下载完毕 将文件写入文件夹

    NSData *data = [NSData dataWithContentsOfURL:filePath];

    [data writeToURL:filePath atomically:YES];
    
        model.localPath = [filePath path];
        if (block)
        {
            block(index);
        }
    }];

    [downloadTask resume];//完全下载文件流程，

   
}
@end
